#!/usr/bin/env python
import cherrypy
from mplayer import MPlayer
import os

class VideoServer(object):
    def index(self, **args):
        p = cherrypy.request.params
        rval = ''
        try:
            if p['action'] in ['play', 'pause', 'load', 'seek', 'listfiles', 'info', 'exit','seekto', 'listdirs', 'channel', 'tv']:
                rval = {'play': playHandler,
                 'pause': pauseHandler,
                 'load': loadHandler,
                 'seek': seekHandler,
                 'seekto': seekToHandler,
                 'listfiles': listHandler,
                 'listdirs': listDirHandler,
                 'info': infoHandler,
                 'channel': changeChannel,
                 'tv': cableCommand,
                 'exit': exitHandler}[p['action']](p)
        except:
            pass
        return rval
    index.exposed = True


def cableCommand(p):
  irsend(p['cmd'])

def changeChannel(p):
  channel(p['channel'])
  print "OK: Changed to %s " % p['channel']

def ListDirectories():
    alldirs = []
    for d in directories:
        for root, dirs, files in os.walk(d):
	    alldirs.append({'path': root, 'name': root.split('/')[-1].replace('_', '')} )
    return "%s" % alldirs
              

def ListFiles(p):
    files = []
    print "%s" % p
    p["path"] = p["path"].replace("-_space_-", " ")
    flist = os.listdir(p["path"])
    flist.sort()
    for f in flist:
        print "%s" % flist
	ext = f.split('.')[-1]
        print ext
        if ext in extensions:
            name = f.replace(".%s" % ext, "").replace("_", " ")
            files.append({"path":"%s/%s" %(p["path"].replace(" ", "%20"),f),"name": name})
    return files

def exitHandler():
    mp.quit()
    return "OK"
    
def seekToHandler(p):
    mp.seek(int(p['pos']), 1)
    return "OK"
    
    
def json(val):
    if val:
        return val
    else:
        return 0
def infoHandler(p):
    return "%s" % {#'file':  json(mp.get_file_name())
                  'percent': json(mp.get_percent_pos())
                 , 'len': json(mp.get_time_length())
                 , 'pos': json(mp.get_time_pos())
                 }


def playHandler(p):
    mp.play()
    return "OK"

def seekHandler(p):
    mp.seek(int(p['diff']))
    return "OK"
    
def pauseHandler(p):
    mp.pause()
    return "OK"

def loadHandler(p):
    file = p["file"].replace("-_space_-", " ")
    print "FILE: %s" % file
    mp.loadfile(file)
    return "OK"

def listHandler(p):
    files = "%s\n" % ListFiles(p)
    return files
    
def listDirHandler(p):
    files = "%s\n" % ListDirectories()
    return files
    


MPlayer.populate()
mp =  MPlayer()



#TV CONTROL STUFF

def channel(n):
  enter = "enter"
  if (str(n)[-1] == '0'):
    n = int(n) + 1
    enter = "enter ch_down"
  irsend("%s %s" % (' '.join(str(n)), enter))

def irsend(cmd):
  os.system("irsend send_once comcast %s" % cmd)


extensions = ['mpg', 'mpeg', 'avi', 'flv', 'mov']

directories = ['/home/michael/Videos']
def main():
    cherrypy.server.socket_host = "127.0.0.1"
    cherrypy.quickstart(VideoServer())

if __name__ == "__main__":
  main()
